﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Net;
using System.Timers;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
using AgentTest;
using DevExpress.XtraBars;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraEditors;
using DevExpress.Utils;
using GeneralDFS.Common.Network;
using GeneralDFS.DataEntity.Config;
using GeneralDFS.Client;
using System.Data.SqlClient;
using GeneralDFS.DataEntity.Nodes;
using GeneralDFS.Interface.Agent;
using NIF.MobileActors.Core;
using NIF.MobileActors.Hosts;
using DXWinFormDataAnalysis.DataModel;

namespace DXWinFormDataAnalysis
{
    public partial class Form1 : XtraForm
    {
        private Client _client;
        private DFSConfig _config;
        private DataTable _dataTable;
        private WaitForm1 wform;
        private SearchNodesActor act;
        private List<NameNodeStatistics> nameNodeStatisticses;

        public Form1()
        {
            InitializeComponent();
            this.Deactivate += Form1_Deactivate;
            this.Activated += Form1_Activated;
            _client = new Client();
            _config = _client.GetConfig();
            _dataTable = new DataTable();
            nameNodeStatisticses = new List<NameNodeStatistics>();
        }

        void Form1_Activated(object sender, EventArgs e)
        {
            if (wform != null)
            {
                wform.WindowState = FormWindowState.Normal;
                wform.Visible = true;
            }
        }



        void InitDataSource()
        {
            NameNodeStatistics nNS;
            int i = 0;
            while (i < act.NameNodeStatistics.Count)
            {
                nNS = new NameNodeStatistics();
                nNS.ServerName = act.NameNodeStatistics[i].NameNodeInfo.ServerName;
                nNS.Ip = act.NameNodeStatistics[i].NameNodeInfo.Ip;
                nNS.RpcPort = act.NameNodeStatistics[i].NameNodeInfo.RpcPort;
                nNS.AgentRpcPort = act.NameNodeStatistics[i].NameNodeInfo.AgentRpcPort;
                nNS.LastUpdateTime = act.NameNodeStatistics[i].NameNodeInfo.LastUpdateTime;
                nNS.BlockCount = act.NameNodeStatistics[i].BlockCount;
                nNS.DataNodeCount = act.NameNodeStatistics[i].DataNodeCount;
                nNS.StatisticTime = act.NameNodeStatistics[i].StatisticTime;
                nNS.Cpu = act.NameNodeStatistics[i].Cpu;
                nNS.Memory = act.NameNodeStatistics[i].Memory;
                nNS.HardDiskSize = act.NameNodeStatistics[i].HardDiskSize;
                nNS.HardDiskRate = act.NameNodeStatistics[i].HardDiskRate;
                nNS.NodeType = "NameNode";
                i++;
                nameNodeStatisticses.Add(nNS);
            }
        }


        private void bt_SearchNodesData_Click(object sender, EventArgs e)
        {
            wform = new WaitForm1();
            //   wform.Location.Offset(Screen.FromControl(this).WorkingArea.Width, Screen.FromControl(this).WorkingArea.Height);
            wform.StartPosition = FormStartPosition.CenterScreen;
            wform.Show();

            ActorProxy<IEntry> localActor = RemotingHost.LocalFacade.CreateLocalActor<IEntry>(typeof(SearchNodesActor));
            act = localActor.GetActor() as SearchNodesActor;
            Client client = new Client();
            Queue<IPEndPoint> hosts = new Queue<IPEndPoint>();
            foreach (NameNodeConfig nameNodeConfig in client.GetConfig().NameNodeConfigs)
            {
                var endPoint = new IPEndPoint(IPAddress.Parse(nameNodeConfig.Ip), nameNodeConfig.AgentRpcPort);
                hosts.Enqueue(endPoint);
            }

            act.Hosts = hosts;
            act.LocalHost = new IPEndPoint(IPAddress.Parse(IPHelper.GetLocalIP("network")), 8820);
            try
            {

                localActor.Post(h => h.Excute());
                ActorProxy<IEntry> actor = RemotingHost.LocalFacade.GetActorProxy<IEntry>(localActor.ID);
                System.Timers.Timer timer = new System.Timers.Timer(10);
                timer.Elapsed += timer_Elapsed;
                timer.Start();
            }
            catch (Exception exception)
            {
                throw exception;
            }

            wform.Load += wform_Load;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var timer = (System.Timers.Timer)sender;
            if (act.IsLastHost)
            {
                try
                {
                    timer.Stop();

                    this.Invoke(new MethodInvoker(delegate
                            {
                                InitDataSource();
                                gridControl1.BeginUpdate();
                                gridControl1.DataSource = nameNodeStatisticses;
                                gridControl1.EndUpdate();
                                if (wform != null && wform.WindowState == FormWindowState.Normal)
                                    wform.Close();
                            }));
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void wform_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Deactivate(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                if (wform != null && wform.WindowState == FormWindowState.Normal)
                {
                    wform.WindowState = FormWindowState.Minimized;
                    wform.Visible = false;
                }
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                if (wform != null && wform.WindowState == FormWindowState.Minimized)
                {
                    wform.WindowState = FormWindowState.Normal;
                    wform.Visible = true;
                }
            }
        }

        private void pivotGridControl_CellDoubleClick(object sender, PivotCellEventArgs e)
        {
            MessageBox.Show(sender.ToString());
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            object row = view.GetRow(e.RowHandle);
            if (e.Button == MouseButtons.Left)
            {
                MessageBox.Show(row.GetType().ToString());
            }
            else
            {
                
              //  BarItem item =new BarToolbarsListItem();
            //    item.Caption = "关机";
             //   barManager1.Items.Add(item);

              
    
                popupMenu_RightKey.ShowPopup(barManager1,new Point(Cursor.Position.X,Cursor.Position.Y));
             
            }

        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (1 + e.RowHandle).ToString();
            }
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ;
            }
            else
            {
                popupMenu_RightKey.ShowPopup(new Point(e.X, e.Y));
            }
        }

       

        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            int[] selected = gridView1.GetSelectedRows();
            if (selected.Length > 0)
            {
                object row = gridView1.GetRow(selected[0]);
                var nameNodeStatistics = (NameNodeStatistics) row;
                GeneralDFS.BusinessLogical.Nodes.NameNode.GetInstance(new NameNodeInfo{Ip = nameNodeStatistics.Ip,RpcPort = nameNodeStatistics.RpcPort,ServerName = nameNodeStatistics.ServerName}).Shutdown();
            }
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            int[] selected = gridView1.GetSelectedRows();
            if (selected.Length > 0)
            {
                object row = gridView1.GetRow(selected[0]);
                var nameNodeStatistics = (NameNodeStatistics)row;
                GeneralDFS.BusinessLogical.Nodes.NameNode.GetInstance(new NameNodeInfo { Ip = nameNodeStatistics.Ip, RpcPort = nameNodeStatistics.RpcPort, ServerName = nameNodeStatistics.ServerName }).Reboot();
            }
        }

        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            int[] selected = gridView1.GetSelectedRows();
            if (selected.Length > 0)
            {
                object row = gridView1.GetRow(selected[0]);
                var nameNodeStatistics = (NameNodeStatistics)row;
                GeneralDFS.BusinessLogical.Nodes.NameNode.GetInstance(new NameNodeInfo { Ip = nameNodeStatistics.Ip, RpcPort = nameNodeStatistics.RpcPort, ServerName = nameNodeStatistics.ServerName }).LogoOff();
            }
        }
    }
}